//
//  CloudViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/20.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

/// 状态标志 0-未诊断 1-诊断中 2-已结束 3-已取消 301-待付款，302-待就诊，303-就诊中，304-结束，305-爽约
enum CloudOrderStatus: Int {
    case all
    case waitPay
    case notStart
    case processing
    case comment
    case cancel
    case refunding
    case refunded
    case reviewed
    
    var statusText: String {
        switch self {
        case .waitPay: return "待支付"
        case .notStart: return "未开始"
        case .processing: return "进行中"
        case .comment: return "待评价"
        case .cancel: return "已取消"
        case .refunding: return "退款中"
        case .refunded: return "已退款"
        case .reviewed: return "已评价"
        case .all: return ""
        }
    }
    
    var statusColor: UIColor? {
        switch self {
        case .waitPay, .notStart: return UIColor(hex: "#F54C4C")
        case .processing: return .main
        case .comment, .cancel: return .textGray
        default: return nil
        }
    }
}

struct CloudOrderModel: HandyJSON {
    var scheduleDate: String?
    var scheduleTime: String?
    /// 科室名称
    var deptName: String?
    /// 医生名称
    var doctorName: String?
    /// 状态标志
    var orderStatus: Int = 0
    /// 预约时间
    var scheduleStart: String?
    /// 医院名称
    var hospitalName: String?
    /// 患者姓名
    var patientName: String?
    /// 患者ID
    var patientId: String?
    /// 订单编号
    var orderNumber: String?
    /// 订单ID
    var orderId: String?
    /// 剩余支付时间
    var remainPayTime: String?
    /// 是否可删除 true-可以删除 false-不可以删除
    var canDelete: Bool = false
    /// 是否可删除 true 可以删除 false 不可以删除
    var canCancel: Bool = false
    /// 是否可以报道
    var canSignIn: Bool = false
    /// 订单金额
    var orderAmount: Double = 0.0
    /// 排队序号
    var queueNum: String?
    /// 剩余等待时间
    var remainTime: String?
    /// 诊断id
    var diagnoseId: String?
    var url: String?
    
    var readyFlag: Int = 0
    var relationId: Int = -1
    
    /// 0-不可以退款 1-可以退款
    var canRefund: Int = 0
}

struct CloudOrderViewModel {
    struct RowViewModel {
        let model: CloudOrderModel
        
        var url: String { return model.url ?? "" }
        
        var orderId: String { return model.orderId ?? "" }
        
        var departmentName: String { return model.deptName ?? "" }
        var doctorName: String { return model.doctorName ?? "" }
        var status: OrderStatus { return OrderStatus(rawValue: model.orderStatus) ?? .all }
//        var scheduleTime: String { return "预约时间：\(model.scheduleStart ?? "")" }
        var diagnoseId: String { return model.diagnoseId ?? "" }
        var canSignIn: Bool { return model.canSignIn }
        
        var readyFlag: Int { return model.readyFlag }
        
        var scheduleTime: String { return model.scheduleTime ?? "" }
        var scheduleDate: String { return model.scheduleDate ?? "" }
        var scheduleStr: String { return "预约时间：\(scheduleDate) \(scheduleTime)" }
        
        var orderNumber: String { return model.orderNumber ?? "" }
        
        /// 排队序号
        var queueNum: String { return model.queueNum ?? "" }
        /// 剩余等待时间
        var remainTime: String { return model.remainTime ?? "" }
        /// 剩余支付时间
        var remainPayTime: String { return model.remainPayTime ?? "" }
        
        /// 0-不可以退款 1-可以退款
        var canRefund: Int { return model.canRefund }
        
        var tipText: NSAttributedString {
            let attributes = [NSAttributedString.Key.foregroundColor: UIColor(hex: "#F54C4C")]
            switch status {
            case .waitPay:
                let timeStr = Date.timeStampToString(timeStamp: remainPayTime.intValue)
                let text = "请在\(timeStr)内完成支付"
                let attrStr = NSMutableAttributedString(string: text)
                attrStr.setAttributes(attributes, range: NSRange(location: 2, length: timeStr.count))
                return attrStr
            case .notStart:
                if readyFlag == 0 {
                    let text = "请在20分钟前来等候"
                    let attrStr = NSMutableAttributedString(string: text)
                    attrStr.setAttributes(attributes, range: NSRange(location: 2, length: 4))
                    return attrStr
                } else {
                    let timeStr = Date.timeStampToString(timeStamp: remainTime.intValue)
                    let text = "您前面还有\(queueNum)人正在排队，预计还要\(timeStr)"
                    let attrStr = NSMutableAttributedString(string: text)
                    attrStr.setAttributes(attributes, range: NSRange(location: 5, length: queueNum.count))
                    attrStr.setAttributes(attributes, range: NSRange(location: 15 + queueNum.count, length: timeStr.count))
                    return attrStr
                }
            case .processing:
                let text = "您的远程门诊已开始，点击进入"
                let attrStr = NSMutableAttributedString(string: text)
                return attrStr
            default:
                let text = ""
                let attrStr = NSMutableAttributedString(string: text)
                return attrStr
            }
        }
        
        var cellHeight: CGFloat { return 150 }
    }
    
    var models: [CloudOrderModel]
    
    var showEmptyView: Bool { return models.count <= 0 }
    
    var numberOfRows: Int { return models.count }
    
    func viewModel(of indexPath: IndexPath) -> RowViewModel {
        return RowViewModel(model: models[indexPath.row])
    }
    
    mutating func loadMore(with models: [CloudOrderModel]) {
        self.models += models
    }
}

extension CloudOrderViewModel {
    static func changeCloudStatus(userId: Int,
                                  diagnoseId: String,
                                  isReady: Int,
                                  finished: @escaping (_ msg: String?, _ code: HttpCode) -> Void)
    {
        let paras: [String: Any] = [
            "userId": userId,
            "id": diagnoseId,
            "isReady": isReady
        ]
        HttpTool.shared.request(target: ApiManager.changeCloudStatus(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
}
